今天延續昨天build出來的專案
新增seed data
dotnet ef migrations add InitialCreate
dotnet ef database update
Main.cs
CreateHostBuilder(args).Build().Run();
//一開始先執行build然後run
var host = CreateHostBuilder(args).Build();
//在執行run之前先初始化seed資料
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
SeedProductData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
host.Run();
因為我們已經將連接字串設定注入到startup.cs裡面了
如果再DbContext override OnConfiguring需要另外加入判斷
db的連線字串不存在時才再去設定檔讀一次
ShopMvcDbContext.cs
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlite(Configuration["ConnectionStrings:ShopMvcContext"]);
}
}